package com.example.javapracticaltraining.controller;

import com.example.javapracticaltraining.entity.R;
import com.example.javapracticaltraining.entity.dto.PasswordChangeDTO;
import com.example.javapracticaltraining.entity.pojo.Users;
import com.example.javapracticaltraining.service.UsersService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import io.swagger.v3.oas.annotations.responses.ApiResponse;
import io.swagger.v3.oas.annotations.responses.ApiResponses;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

@Tag(name = "个人中心", description = "提供用户个人信息查询和更新功能")
@RestController
@RequestMapping("/personalCenter")
public class PersonalCenterController {

    @Autowired
    private UsersService usersService;

    @Operation(summary = "获取用户信息", description = "根据用户ID获取用户个人信息")
    @ApiResponses(value = {
        @ApiResponse(responseCode = "200", description = "成功获取用户信息"),
        @ApiResponse(responseCode = "500", description = "用户不存在")
    })
    @GetMapping("/{userId}")
    public R<Users> getUserInfo(
            @Parameter(description = "用户ID", required = true) @PathVariable Integer userId) {
        Users user = usersService.getById(userId);
        if (user == null) {
            return R.error("用户不存在");
        }
        // 敏感信息不返回给前端
        user.setPassword(null);
        return R.success(user);
    }

    @Operation(summary = "更新用户信息", description = "更新用户个人信息（不包括密码）")
    @ApiResponses(value = {
        @ApiResponse(responseCode = "200", description = "个人信息更新成功"),
        @ApiResponse(responseCode = "500", description = "个人信息更新失败")
    })
    @PutMapping
    public R<String> updateUserInfo(@RequestBody Users user) {
        // 密码不通过此接口修改
        user.setPassword(null);
        boolean success = usersService.updateById(user);
        if (success) {
            return R.success("个人信息更新成功");
        } else {
            return R.error("个人信息更新失败");
        }
    }

    @Operation(summary = "修改密码", description = "修改用户密码")
    @ApiResponses(value = {
        @ApiResponse(responseCode = "200", description = "密码修改成功"),
        @ApiResponse(responseCode = "500", description = "密码修改失败")
    })
    @PutMapping("/password")
    public R<String> changePassword(@RequestBody PasswordChangeDTO passwordChangeDTO) {
        return usersService.changePassword(passwordChangeDTO);
    }
}
